package com.program.houai.pay;

/**
 * @version v1.0
 * @ProjectName: hou
 * @ClassName: MD5Util
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/9/15 9:14
 */
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class MD5Util {

    public static  String getSign(Map<String, Object> data,String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            sb.append(k).append("=").append(data.get(k)).append("&");

        }
        sb.append("key=").append(key);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] array = new byte[0];
        try {
            array = md.digest(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuilder sb2 = new StringBuilder();
        for (byte item : array) {
            sb2.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb2.toString().toUpperCase();
    }

    public static  String getSign1(Map<String, Object> data) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            sb.append(k).append("=").append(data.get(k)).append("&");
        }
        sb.append("key=").append("8746a89f2c615448bcbbbe7047e853e7");
        String result = DigestUtils.md5Hex(sb.toString());
        return result.toUpperCase();
    }

    public static String sign2(SortedMap<String, Object> parameters, String key) {
        StringBuilder sb = new StringBuilder();
        for (String k : parameters.keySet()) {
            sb.append(k).append("=").append(parameters.get(k)).append("&");
        }
        sb.append("key=").append(key);

        return DigestUtils.md5Hex(sb.toString()).toUpperCase();
    }

}